package com.yc.servlet;

import com.yc.dao.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * @author: zh
 * @date: 2022/3/10 15:34
 * @version: 1.0
 */
@WebServlet("/userServlet")
public class UserServlet extends BasicServlet {

    DBHelper dbHelper = new DBHelper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        System.out.println("接收到来自前端的请求了");

        //接收来自前端的数据
        String op = req.getParameter("op");
        if (op.equals("login")){
            login(req,resp);
        }

    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //根据用户名查询是否存在用户
        String sql = "select * from users where username = ?";
        List<Map<String, String>> user = dbHelper.find(sql, username);
        if (user.size() <= 0){
            Random random = new Random();
            String nickName = "默认用户"+ (random.nextInt(100000)+100000);
            String sql2 = "insert into users values(null,?,?,?,1,'images/banner1.jpg')";
            int i = dbHelper.doUpdate(sql2, nickName, username, password);
            if (i > 0) {
                this.send(resp, nickName);
            }else {
                this.send(resp, -1);
            }
        }else {
            if (user.get(0).get("pwd").equals(password)){
                this.send(resp, user.get(0).get("nick_name"));
            }else {
                this.send(resp, -2);
            }
        }
    }
}
